//
//  MapGPSViewController.m
//  DataStatistics
//
//  Created by oilklenze on 15/11/3.
//  Copyright © 2015年 YTYangK. All rights reserved.

//列表gps
#import "Annotation.h"
#import "CanlloutAnnotationView.h"
#import "JZLocationConverter.h"
#import "KCAnnotation.h"
#import "MapGPSViewController.h"
#import "PPQueryGpsModel.h"
#import <pop/POP.h>
#import <AFNetworking.h>
#import "NetRequestClass.h"
#import "UtilToolsClass.h"
@interface MapGPSViewController () <MKMapViewDelegate> {

    CLGeocoder* _geocoder;
    BOOL _firstDisplay;
}

@property (strong, nonatomic) CLLocationManager      * locationManager;
@property (strong, nonatomic) NSMutableArray         * annotationaArray;
@property (nonatomic        ) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) CanlloutAnnotationView * annotationView;
@property(nonatomic,strong) PPQueryGpsModel * gpsModel; // 数据模型
@end

@implementation MapGPSViewController
#pragma mark - 属性设置
- (NSMutableArray*)annotationaArray{
    if (!_annotationaArray) {
        _annotationaArray = [[NSMutableArray alloc] init];
    }
    return _annotationaArray;
}

- (MKMapView*)mapview{
    if (!_mapview) {
        _mapview = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
         _mapview.delegate = self;
        _mapview.userTrackingMode = MKUserTrackingModeFollow; // 跟随者 配合CLLocationManger使用
        _mapview.mapType = MKMapTypeStandard; // 地图类型
    }
    return _mapview;
}

- (AddressView *)addresView{
    if (!_addresView) {
        _addresView       = [[AddressView alloc]init];
        _addresView.frame = CGRectMake(20, -52 - 64, SCREEN_WIDTH - 40, 52);
        [self.mapview addSubview:_addresView];
        [_addresView.navigationBtm addTarget:self action:@selector(mapNavigationBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addresView;
}



- (void)viewDidLoad{
    [super viewDidLoad];
    [self setTitle:@"GPS"];
    _firstDisplay = YES;

    // 设置返回按钮
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.hidesBackButton = YES;
    
    /*          定位      */
    [self initLocationManager];
    /*          添加地图      */
    [self.view addSubview:self.mapview];
    
    if (self.isEnterSetting) {
        // 从设置界面进来。只需要显示公司坐标
        [self addAnnotationForCompanyLocaltion];
    }else{
        /*      获取数据   */
        [self dataRequest];
    }
    /*      自己位置图标    */
    [self addmyLocation];
}



- (void)backItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark  显示公司地址
- (void)addAnnotationForCompanyLocaltion{
    
    MKPointAnnotation* annotation  = [[MKPointAnnotation alloc] init];
    annotation.title = NSLocalizedString(@"英特路(中国)机械设备有限公司",nil);
    annotation.subtitle = NSLocalizedString(@"珠海市南屏科技园虹达路3号", nil);
    annotation.coordinate        = CLLocationCoordinate2DMake(22.2193070000,113.4869010000);
    [self.mapview addAnnotation:annotation];
    [self.mapview showAnnotations:@[annotation] animated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            CLLocationCoordinate2D newCoordinate =     [self mapCenterCoordinate:annotation.coordinate withOffsetXPixelSize:CGSizeMake(-60, 0)];
            [self.mapview setCenterCoordinate:newCoordinate animated:YES];
        });
}

 #pragma mark 开始定位
-(void) initLocationManager{
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        //在ios 8.0下要授权
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
                [self.locationManager requestWhenInUseAuthorization];// 前台定位
     }
    }else {
        [self authorizationStatus];
    }
    // 开始定位
//    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [self.locationManager startUpdatingLocation];
}

#pragma mark - custom method 自定义方法
- (BOOL)authorizationStatus{
    if (!([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) && !([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        UIAlertController *authorizationStatusAler =[UtilToolsClass addAlertControllerForAuthorizationStatus:NSLocalizedString(@"请打开系统设置中\"隐私->定位->服务\",允许\"ILS Monitor\"使用您的位置", nil) ];
        [self presentViewController:authorizationStatusAler animated:YES completion:nil];
        return NO;
    }else {
        return YES;
    }
}

#pragma  mark       ***************** 数据请求 ,获取单台设备的GPS经纬度     *****************
- (void)dataRequest{
    NSString* urlString  = [REQUESTHEADER stringByAppendingString:@"deviceGps/queryDeviceGPS.asp"];
    [NetRequestClass requestWithURLForQueryDeviceGPS:self andUrl:urlString andParam:@{@"i_imei" : self.device_IMEI} success:^(PPQueryGpsModel *result) {
        if (result) {
            
            [self addAnnotation:result];
        }
    } failure:^(NSString *failure) {
        [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
    }];
}



//数据处理并添加大头针
- (void)addAnnotation:(PPQueryGpsModel *)model{
    self.gpsModel = model;
    
    KCAnnotation* annotation  = [[KCAnnotation alloc] init];
    annotation.name =  self.gpsModel.d_name;
    annotation.deviceType  =  self.gpsModel.d_type;
    annotation.upload_time = self.gpsModel.i_recvTime;
    
    CLLocationCoordinate2D Gcj02 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(self.gpsModel.i_latitude_n, self.gpsModel.i_longitude_e)];
    
//        CLLocationCoordinate2D Gcj02=CLLocationCoordinate2DMake(self.gpsModel.i_latitude_n,self.gpsModel.i_longitude_e);

    
    
    annotation.coordinate        = Gcj02;
    self.coordinate              = Gcj02;
    annotation.icon = [UIImage imageNamed:@"在线标记"];
    if (Gcj02.latitude != 0.0f && Gcj02.longitude !=0.0f) {
        [self.mapview addAnnotation:annotation];
        [self.annotationaArray addObject:annotation];
        _firstDisplay ? [self.mapview showAnnotations:self.annotationaArray animated:YES] :nil;
        _firstDisplay = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            CLLocationCoordinate2D newCoordinate =     [self mapCenterCoordinate:annotation.coordinate withOffsetXPixelSize:CGSizeMake(-40, 0)];
       
            [self.mapview setCenterCoordinate:newCoordinate animated:YES];
        });
        CLLocationCoordinate2D coord = annotation.coordinate;
        MKCoordinateSpan span = { 0.05, 0.05 };
        MKCoordinateRegion region = { coord, span };
        [self.mapview setRegion:region animated:YES];
    }
}

//设置定位自己按钮
- (void)addmyLocation
{
    UIButton* myLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    myLocation.frame = CGRectMake(30,  [UIScreen mainScreen].bounds.size.height - 180, 62, 62);
    [myLocation setBackgroundImage:[UIImage imageNamed:@"标记按钮"] forState:UIControlStateNormal];
    [myLocation addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.mapview addSubview:myLocation];
}


#pragma mark    *********** 点击按钮显示自己位置 ************
- (void)clickButton:(UIButton*)button{
    if (!self.mapview.userLocation.location) {
        return;
    }
    if ([self authorizationStatus]) {
        CLLocationCoordinate2D coord = self.mapview.userLocation.coordinate;
        MKCoordinateSpan span = { 0.05, 0.05 };
        MKCoordinateRegion region = { coord, span };
        [self.mapview setRegion:region animated:YES];
    }
}

// 计算地图按像素位移   设置地图中心点的位置
- (CLLocationCoordinate2D)mapCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate withOffsetXPixelSize:(CGSize)size
{
    CGFloat pixelsPexDegreeLet = SCREEN_HEIGHT-64 / self.mapview.region.span.latitudeDelta;
    CGFloat pixelsPerDegreeLon = SCREEN_WIDTH / self.mapview.region.span.longitudeDelta;
    
    CLLocationDegrees offsetLonDegree = size.width / pixelsPerDegreeLon;
    CLLocationDegrees offsetLatDegree = size.height / pixelsPexDegreeLet;
    CLLocationCoordinate2D newCoordinate = {
        centerCoordinate.latitude + offsetLatDegree,
        centerCoordinate.longitude + offsetLonDegree
    };
    return newCoordinate;
}

#pragma mark - 代理
#pragma mark MapViewDeledate
// 在大头针显示重绘的时候调用，常用于更改大头针的类型
- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
 
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString* identifier = @"CustAnnotation";
        self.annotationView = (CanlloutAnnotationView*)[self.mapview dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (self.annotationView == nil) {
            self.annotationView = [[CanlloutAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        }
        self.annotationView.annotation     = (KCAnnotation*)annotation;
        self.annotationView.image          = ((KCAnnotation*)annotation).icon ;
        self.annotationView.enabled        = YES;
        self.annotationView.canShowCallout = NO;
        self.annotationView.centerOffset   = CGPointMake(0, 0);
        if (!self.isEnterSetting) {
            [self.annotationView setSingleLabelText:(KCAnnotation*)annotation];
        }
        return self.annotationView;
    }
    else {
        MKAnnotationView * annotationView = [[MKAnnotationView alloc] init];
        if ([annotation.title isEqualToString:@"英特路(中国)机械设备有限公司"]) {
            annotationView.annotation = annotation;
            annotationView.image = [UIImage imageNamed:@"在线标记@3x"];
            annotationView.enabled        = YES;
            annotationView.canShowCallout = YES;
            return annotationView;   // 返回系统自定义的
        }
        return nil;
    }
}


//出来就显示大头针上面的view
- (void)mapView:(MKMapView*)mapView didAddAnnotationViews:(nonnull NSArray<MKAnnotationView*>*)views{

    for (id myAnnotation in mapView.annotations) {
        if (![myAnnotation isKindOfClass:[MKUserLocation class]]) {
            [mapView selectAnnotation:myAnnotation animated:YES];
        }
    }
}


#pragma mark  触发大头针后，回调此处。显示地址
- (void)mapView:(MKMapView*)mapView didSelectAnnotationView:(MKAnnotationView*)view{
    POPSpringAnimation* anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    anim.fromValue           = [NSValue valueWithCGRect:CGRectMake(1, 1, 1, 1)];
    anim.toValue             = [NSValue valueWithCGRect:CGRectMake(- 160, -77, 240, 80)];
    anim.springBounciness    = 10;
    anim.springSpeed         = 8;
    [self.annotationView.view pop_addAnimation:anim forKey:nil];
    [AddressView getAddressByLatitude:view.annotation.coordinate.latitude longitude:view.annotation.coordinate.longitude  addrees:^(NSDictionary *placemark) {
        NSString * addressArr = placemark[@"City"];
        addressArr =  [addressArr stringByAppendingString:placemark[@"SubLocality"]];
       addressArr =  [addressArr stringByAppendingString:placemark[@"Name"]];
//       addressArr =  [addressArr stringByAppendingString:placemark[@"SubLocality"]];
        [self.addresView labelSetAddress:addressArr];
        NSLog(@"---  地址：%@",addressArr);
    }];
    [self.addresView addAppearAnimationByBeginFrame:self.addresView.frame finishFrame:CGRectMake(20, 0, self.addresView.size.width, self.addresView.size.height)];
}





//弹窗选项导航地图 没有激活此方法 可以删除
- (void)mapNavigationBtn:(UIButton*)button
{
    NSString* title                   = [NSString stringWithFormat:NSLocalizedString(@"导航到设备", nil)];
    UIAlertController* alerController = [UIAlertController alertControllerWithTitle:title
                                                                            message:nil
                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction       = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消",nil)
                                                                 style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction* gaodeMapAction     = [UIAlertAction actionWithTitle:NSLocalizedString(@"高德地图",nil)
                                                                 style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction* _Nonnull action) {
    NSString* urlsting = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2", self.coordinate.latitude, self.coordinate.longitude]
                              stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    CLLocationCoordinate2D bd09   = [JZLocationConverter gcj02ToBd09:self.coordinate];// 将火星坐标系（中国国测局坐标系）转成百度坐标系
    UIAlertAction* baiduMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"百度地图",nil)
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {
    NSString* urlsting            = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02", bd09.latitude, bd09.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    UIAlertAction* googleMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Google地图",nil)
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction* _Nonnull action) {
    NSString* urlsting             = [[NSString stringWithFormat:@"comgooglemaps://?x-source= &x-success= &saddr=&daddr=%f,%f&directionsmode=driving", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    UIAlertAction* ownMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"自带地图",nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction* _Nonnull action) {

    MKMapItem* currentLocation  = [MKMapItem mapItemForCurrentLocation];
    MKMapItem* toLocation       = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:self.coordinate addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[ currentLocation, toLocation ] launchOptions:@{
                                                                                  MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
                                                                                  MKLaunchOptionsShowsTrafficKey : [NSNumber numberWithBool:YES]
                                                                                      }];
    }];

    [alerController addAction:cancelAction];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        [alerController addAction:baiduMapAction];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alerController addAction:gaodeMapAction];
    };
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        [alerController addAction:googleMapAction];
    }
    [alerController addAction:ownMapAction];
    if (objc_getClass("UIAlertController") != nil) {
        [self presentViewController:alerController animated:YES completion:nil];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请升级系统版本后用此功能"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
}



@end
